package com.yang.qgg_demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yang.qgg_demo.common.R;
import com.yang.qgg_demo.entity.Goods;
import com.yang.qgg_demo.entity.User;
import com.yang.qgg_demo.mapper.GoodsMapper;
import com.yang.qgg_demo.service.GoodsService;
import com.yang.qgg_demo.utils.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.stream.Collectors;



/**
 * 菜品管理
 */
@RestController
@RequestMapping("/goods")
@Slf4j
public class GoodsController {
    @Autowired
    private GoodsService goodsService;

    @Autowired
    private GoodsMapper goodsMapper;


    /**
     * 新增商品
     * @param goods
     * @return
     */
    @PostMapping("/save")
    public R<String> save(@RequestBody Goods goods){

        log.info(goods.toString());
        goods.setProfit(goods.getPrice()-goods.getPerchaseprice());

        if (goodsService.saveOrUpdate(goods)){
            return R.success("成功建立");
        }

        return R.error("新增商品失败");
    }

    /**
     * 分页查询
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public Page<Goods> findPage( @RequestParam Integer pageNum, @RequestParam Integer pageSize,String name) {

        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
        Page pageInfo=new Page(pageNum, pageSize);
        queryWrapper.like(StringUtils.isNotEmpty(name),Goods::getCode,name);
//        queryWrapper.orderByAsc(sort.isEmpty());

        log.info(String.valueOf(goodsService.page(pageInfo,queryWrapper)));
        return goodsService.page(pageInfo,queryWrapper);
    }

    @DeleteMapping("/{id}")
    public R delete(@PathVariable Integer id) {
        log.info(String.valueOf(id));
        if (goodsService.removeById(id)){
            return R.success("删除成功");
        }
        return R.error("删除失败");
    }


}

